package com.gitee.wsl.ext.db

import androidx.collection.mutableScatterMapOf
import androidx.sqlite.SQLiteConnection
import androidx.sqlite.SQLiteStatement

object Database {
    suspend fun databaseSize(connection: SQLiteConnection): Long {
        return connection.prepare( "SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size();").getLong(0)
    }

//    internal suspend fun checkSchema(driver: SqlDriver) {
//        val tableNames = mutableListOf<String>()
//        try {
//            // https://sqlite.org/forum/info/d90adfbb0a6eea88
//            // The name is sqlite_schema these days but older versions use sqlite_master and sqlite_master is recognized everywhere so use that
//            executeQuery(driver, "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;") { cursor ->
//                cursor.getString(0)!!
//            }.awaitAsList().forEach { tableName ->
//                tableNames.add(tableName)
//            }
//        } catch (e: Exception) {
//            apolloExceptionHandler(Exception("An exception occurred while looking up the table names", e))
//            /**
//             * Best effort: if we can't find any table, open the DB anyway and let's see what's happening
//             */
//        }
//
//        val expectedTableName = "record"
//        check(tableNames.isEmpty() || tableNames.contains(expectedTableName)) {
//            "Apollo: Cannot find the '$expectedTableName' table (found '$tableNames' instead)"
//        }
//    }


}


/**
 * A tentative to approximate the Sqlite LIKE operator with Regexes
 */
internal fun patternToRegex(pattern: String): Regex {
    val regex = buildString {
        var pendingEscape = false
        for (i in pattern.indices) {
            val cur = pattern[i]
            when {
                pendingEscape -> {
                    when {
                        cur == '\\' -> append("\\\\") // an escaped backslash is also an escape backslash in a regex
                        cur == '%' -> append("%")
                        cur == '_' -> append("_")
                        else -> error("Invalid escape in pattern: $pattern")
                    }
                }

                cur == '\\' -> pendingEscape = true
                cur == '%' -> append(".*")
                cur == '_' -> append(".")
                else -> {
                    if (specialChars.contains(cur)) {
                        // this needs to be escaped in the regex
                        append("\\")
                    }
                    append(cur)
                }
            }
        }
    }

    return Regex(regex, option = RegexOption.IGNORE_CASE)
}

private val specialChars = "()^$.*?+{}"
